package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@Api(description = "获取代办事项中的红点")
@RestController
@RequestMapping("/redDotsController")
public class RedDotsController {

    private static final Logger logger = LoggerFactory.getLogger(RedDotsController.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ReportRedDotRepository reportRedDotRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Autowired
    private ComplaintReportRepository complaintReportRepository;


    @ApiOperation("获取代办事项中的红点")
    @RequestMapping(value = "getRedDots", method = RequestMethod.GET)
    public JsonResponse getRedDots(Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        if (clientUser.getUserType().equals(UserType.customer)) {
            return JsonResponse.successResponse();
        }
        Integer[] dots = new Integer[5];
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        String[] str = new String[2];
        str[0] = Constants.MANAGE_DEPARTMENT_UNREAD;
        str[1] = Constants.MANAGE_DEPARTMENT_EDIT;
        builder.and(qStationReport.specifiedType.in(str));
        List<StationReport> stationReportList = (List<StationReport>) stationReportRepository.findAll(builder);
        Long[] reportIds = new Long[stationReportList.size()];
        for (int i = 0; i < stationReportList.size(); i++) {
            reportIds[i] = stationReportList.get(i).getId();
        }
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
//        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.regularReport.id.in(reportIds));
        List<CustomerRegularReport> customerRegularReports = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builder);
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.SERVICE_REPORT_FOLLOW_UP);
        boolean b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            logger.info("此用户没有常规报告审核权限");
            dots[0] = 0;
        } else {
            dots[0] = customerRegularReports.size();
        }


        UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "当前用户信息不全");
        }
        List<Department> department = userProfile.getDepartmentList();

        if (department == null || department.size() == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "当前用户没有绑定任何部门，请先绑定部门");
        }
        List<Long> departmentIds = new ArrayList<>();
        for (Department id : department) {
            departmentIds.add(id.getId());
        }
        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        if (!userProfile.isAdmin()) {
            builder.and(qReportRedDot.departmentId.in(departmentIds));
        }
//        builder.and(qReportRedDot.stationReport.exceptionType.eq(Constants.DEPARTMENT_UNREAD));
        builder.and(qReportRedDot.type.eq(Constants.DEPARTMENT_UNREAD));
//        builder.and(qReportRedDot.readed.eq(false));
        List<ReportRedDot> redDots = (List<ReportRedDot>) reportRedDotRepository.findAll(builder);
        m = moduleAuthorityRepository.findByName(Constants.SERVICE_REPORT_AUDIT);
        b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            logger.info("此用户没有常规报告跟进权限");
            dots[1] = 0;
        } else {
            dots[1] = redDots.size();
        }

        QAuditReport qAuditReport = QAuditReport.auditReport;
        builder = new BooleanBuilder();
        builder.and(qAuditReport.deleted.eq(false));
        builder.and(qAuditReport.enabled.eq(true));
        builder.and(qAuditReport.category.eq(Constants.TECHCOLOR_REPORT));
        builder.and(qAuditReport.auditing.eq(Constants.AUDIT_APPLY));
        builder.and(qAuditReport.supplement.eq(false));
        List<AuditReport> stationReports = (List<AuditReport>) auditReportRepository.findAll(builder);
        m = moduleAuthorityRepository.findByName(Constants.COLOR_REPORT_AUDIT);
        b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            logger.info("此用户没有维修站技术颜色能力分析报告审核权限");
            dots[2] = 0;
        } else {
            dots[2] = stationReports.size();
        }

        QComplaintReport qComplaintReport = QComplaintReport.complaintReport;
        builder = new BooleanBuilder();
        builder.and(qComplaintReport.deleted.eq(false));
        builder.and(qComplaintReport.enabled.eq(true));
        builder.and(qComplaintReport.audit.eq(false));
        builder.and(qComplaintReport.auditFalse.eq(false));
        builder.and(qComplaintReport.reportStatus.eq(Constants.BEGIN));
        List<ComplaintReport> complaintReportList = (List<ComplaintReport>) complaintReportRepository.findAll(builder);
        Integer size = (Integer) getBackComplaintDots(principal).getData();
        m = moduleAuthorityRepository.findByName(Constants.COMPLAINT_AUDIT_WECHAT);
        b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            logger.info("此用户没有投诉审核（微信端）权限");
            dots[3] = 0;
        } else {
            dots[3] = complaintReportList.size() + size;
        }


        qComplaintReport = QComplaintReport.complaintReport;
        builder = new BooleanBuilder();
        builder.and(qComplaintReport.deleted.eq(false));
        builder.and(qComplaintReport.enabled.eq(true));
        builder.and(qComplaintReport.audit.eq(true));
        builder.and(qComplaintReport.back.eq(false));

        BooleanBuilder orBuilder = new BooleanBuilder();
        orBuilder.or(qComplaintReport.needUserList.any().eq(clientUser.getId()));
        orBuilder.or(qComplaintReport.leader.eq(clientUser.getId()));
        builder.and(orBuilder);
        orBuilder = new BooleanBuilder();
        orBuilder.or(qComplaintReport.reportStatus.eq(Constants.BEGIN));
        builder.and(orBuilder);
        builder.and(qComplaintReport.receive.eq(false));
        complaintReportList = (List<ComplaintReport>) complaintReportRepository.findAll(builder);
        size = (Integer) getComplaintDots(principal).getData();
        m = moduleAuthorityRepository.findByName(Constants.COMPLAINT_FOLLOW_WECHAT);
        b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            logger.info("此用户没有投诉跟进（微信端）权限");
            dots[4] = 0;
        } else {
            dots[4] = complaintReportList.size() + size;
        }

        return JsonResponse.successResponseWithData(dots);
    }


    @ApiOperation("获取我的待跟进报告红点")
    @RequestMapping(value = "getMyServiceRedDots", method = RequestMethod.GET)
    public JsonResponse getMyServiceRedDots(Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.specifiedType.eq(Constants.DEPARMENT_PEDING));
        builder.and(qStationReport.user.id.eq(clientUser.getId()));
        builder.and(qStationReport.deparmentIds.isNotNull());
        List<StationReport> stationReportList = (List<StationReport>) stationReportRepository.findAll(builder);
        return JsonResponse.successResponseWithData(stationReportList.size());
    }

    @ApiOperation("获取代办事项中，待确认与需要再次跟进的报告数量")
    @RequestMapping(value = "getEditDepartment", method = RequestMethod.GET)
    public JsonResponse getEditDepartment(Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        if (clientUser.getUserType().equals(UserType.customer)) {
            return JsonResponse.successResponse();
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.SERVICE_REPORT_AUDIT);
        boolean b = clientUser.getAuthorities().contains(m);
        Integer[] dots = new Integer[2];
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.specifiedType.eq(Constants.MANAGE_DEPARTMENT_UNREAD));
        List<StationReport> stationReportList = (List<StationReport>) stationReportRepository.findAll(builder);
        if (b == false) {
            logger.info("此用户没有常规报告审核权限");
            dots[0] = 0;
        } else {
            dots[0] = stationReportList.size();
        }

        builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.specifiedType.eq(Constants.MANAGE_DEPARTMENT_EDIT));
        stationReportList = (List<StationReport>) stationReportRepository.findAll(builder);
        if (b == false) {
            logger.info("此用户没有常规报告审核权限");
            dots[1] = 0;
        } else {
            dots[1] = stationReportList.size();
        }
        return JsonResponse.successResponseWithData(dots);
    }

    @ApiOperation("获取投诉报告处理中的报告")
    @RequestMapping(value = "getComplaintDots", method = RequestMethod.GET)
    public JsonResponse getComplaintDots(Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QComplaintReport qComplaintReport = QComplaintReport.complaintReport;
        booleanBuilder.and(qComplaintReport.deleted.eq(false));
        booleanBuilder.and(qComplaintReport.enabled.eq(true));
        booleanBuilder.and(qComplaintReport.audit.eq(true));
        booleanBuilder.and(qComplaintReport.back.eq(false));
        booleanBuilder.and(qComplaintReport.auditFalse.eq(false));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.COMPLETE));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.STOP));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.TIME_OUT));
        booleanBuilder.and(qComplaintReport.receive.eq(true));
        booleanBuilder.and(qComplaintReport.followUser.id.eq(clientUser.getId()));
        List<ComplaintReport> complaintReportList = (List<ComplaintReport>) complaintReportRepository.findAll(booleanBuilder);
        return JsonResponse.successResponseWithData(complaintReportList.size());
    }

    @ApiOperation("获取投诉报告审核返回投诉的报告")
    @RequestMapping(value = "getBackComplaintDots", method = RequestMethod.GET)
    public JsonResponse getBackComplaintDots(Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.COMPLAINT_AUDIT_WECHAT);
        boolean b = clientUser.getAuthorities().contains(m);
        if (!b) {
            return JsonResponse.successResponseWithData(0);
        }
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QComplaintReport qComplaintReport = QComplaintReport.complaintReport;
        booleanBuilder.and(qComplaintReport.deleted.eq(false));
        booleanBuilder.and(qComplaintReport.enabled.eq(true));

        BooleanBuilder orBuilder = new BooleanBuilder();
        orBuilder.or(qComplaintReport.reportStatus.eq(Constants.TIME_OUT));
        orBuilder.or(qComplaintReport.reportStatus.eq(Constants.STOP));
        orBuilder.or(qComplaintReport.reportStatus.eq(Constants.OTHER_FOLLOW));
        orBuilder.or(qComplaintReport.reportStatus.eq(Constants.BEGIN));
        booleanBuilder.and(qComplaintReport.back.eq(true));
        booleanBuilder.and(orBuilder);

        List<ComplaintReport> complaintReportList = (List<ComplaintReport>) complaintReportRepository.findAll(booleanBuilder);
        return JsonResponse.successResponseWithData(complaintReportList.size());
    }


}
